<?php
use Facebook\FacebookSession;

use Facebook\FacebookRedirectLoginHelper;

use Facebook\FacebookRequest;

use Facebook\FacebookResponse;

use Facebook\FacebookSDKException;

use Facebook\FacebookRequestException;

use Facebook\FacebookAuthorizationException;

use Facebook\GraphObject;

use Facebook\GraphUser;

use Facebook\GraphSessionInfo;


class Login extends Controller{

	function __construct(){
		parent::__construct();
	}

	function index() {
		$this->view->render('Page/login',false,true);
	}

	function run(){

		$this->model->run();
	}

	function logout(){
		Session::init();
		Session::destroy();
		header('location: ../');
		exit;
	}

	function fblogin () {

		FacebookSession::setDefaultApplication(IDFB, SECRETFB);
		$helper = new FacebookRedirectLoginHelper(URL.'Login/fblogin');


		// see if a existing session exists
		if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
		  // create new session from saved access_token
		  $session = new FacebookSession( $_SESSION['fb_token'] );
		  
		  // validate the access_token to make sure it's still valid
		  try {

		    if ( !$session->validate() ) {
		      $session = null;
		    }
		  } catch ( Exception $e ) {
		    // catch any exceptions
		    $session = null;
		  }
		}  
		 
		if ( !isset( $session ) || $session === null ) {
		  // no session exists
		  
		  try {
		    $session = $helper->getSessionFromRedirect();
		  } catch( FacebookRequestException $ex ) {
		    // When Facebook returns an error
		    // handle this better in production code
		    print_r( $ex );
		  } catch( Exception $ex ) {
		    // When validation fails or other local issues
		    // handle this better in production code
		    print_r( $ex );
		  }
		  
		}
		 
		// see if we have a session
		if ( isset( $session ) ) {
		  	// save the session
		  	$graphObject = $this->f->get_profile_fb($session,'/me');
		  	// print profile data
		  	//$photoObject = $this->f->get_profile_fb($session, '/me/albums');
		 
		  	//if(!empty($photoObject)){
			//  	foreach ($photoObject["data"] as $key) {
			//  		if($key->name == "Cover Photos") {
			//	  		$request = new FacebookRequest(
			//				$session,
			//				'GET',
			//				'/'.$key->id.'/photos',
			//				array (
			//				'url' => '{image-url}',
			//			));
			//			$response = $request->execute();
			//			$abc = $response->getGraphObject()->asArray();
			//			echo '<pre>';
			//		  		print_r($abc['data'][0]->picture);
			//	  	}
			// 	}	
		  	//}
		  	$this->loadModel('QuerySql');
			$name = 'QuerySql_model';
			$this->_query_sql = new $name;

			$sql = "SELECT Id FROM users WHERE IdFacebook = :IdFacebook ";
			$stmt = array(
				':IdFacebook' 	=> 	$graphObject['id']
			);

			$email = "";

		  	$check_user = $this->_query_sql->xhrExecuteQery($sql,$stmt);
				//$location = explode ( ',',$graphObject['location']->name)[0];
		  		//$sql = "SELECT Id FROM citys WHERE  MATCH(Name) AGAINST(:location)";
		  		//$stmt = array(
				//	':location' 	=> 	$location
				//);
				//$abc = $this->_query_sql->xhrExecuteQerySelect($sql,$stmt);
				
		  	if($check_user == 0)
		  	{

	  			//$birthday = $this->f->convert_date($graphObject['birthday']);
	  			$birthday = '1990-03-28';
	  			$UserIpAddress = $this->f->getRealIPAddress();
		  		if(isset($graphObject['email'])) $email = $graphObject['email'];
		  		$sql = "INSERT INTO users (FirstName,LastName,Email,Password,Gender,IdFacebook,NickName,Birthday,CurrentCity)
							VALUES (:FirstName,:LastName,:Email,:Password,:Gender,:IdFacebook,:NickName,:Birthday,:CurrentCity)";
				$stmt = array(
					":FirstName"		=> $graphObject['first_name'],
					":LastName"			=> $graphObject['last_name'],
					":Email"			=> $email,
					":Password"			=> md5('123456'),
					":Gender"			=> $graphObject['gender'],
					":IdFacebook"		=> $graphObject['id'],
					":NickName"			=> $graphObject['name'],
					":Birthday"			=> $birthday,
					":CurrentCity"		=> $graphObject['location']->name
				);
				$this->_query_sql->xhrExecuteQery($sql,$stmt);
		  	}
		  	// print logout url using session and redirect_uri (logout.php page should destroy the session)
		  	$_SESSION["loggerIn"] 	= true;
			$_SESSION["id"] 		= $graphObject['id'];
			$_SESSION["FirstName"] 	= $graphObject['name'];
			$_SESSION["email"] 		= $email;
			$_SESSION["img_icon"] 	= "https://graph.facebook.com/" . $graphObject['id'] . "/picture?width=200&height=200";
			$_SESSION["img_normal"] = "https://graph.facebook.com/" . $graphObject['id'] . "/picture?width=200&height=200";
			$_SESSION["img_large"] 	= "https://graph.facebook.com/" . $graphObject['id'] . "/picture?width=200&height=200";
			header('location: '.URL);
		}else {
		  	// show login url
		  	$permissions = array(
			  'email',
			  'user_location',
			  'user_birthday',
			  'read_friendlists',
			  'user_photos',
			  'user_relationships'
			);
		  	// show login url
		  	echo "<script>window.top.location.href='" . $helper->getLoginUrl($permissions) . "'</script>";
		}

	}
}
?>